﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace B.S.BasicData.Api.Write.Filters
{
    /// <summary>
    /// 访问token授权过滤器
    /// </summary>
    public class AccessTokenFilter : Attribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var claims = context.HttpContext.User.Claims;
            var exp = claims.Where(x => x.Type == "exp").FirstOrDefault()?.Value ?? "0";
            var exp_time = long.Parse(exp);//秒的unix时间戳
            var current_time = DateTimeOffset.UtcNow.ToUnixTimeSeconds();//也是到秒的时间戳

            if (exp_time < current_time) {
                context.Result = new UnauthorizedObjectResult("访问token已经过期");
            }
        }
    }
}
